<template>
  <div class="shop-analysis">
    <!-- Title section -->
    <div class="header-section">
      <h1 class="main-title">Shop Data Monitor</h1>
      <p class="sub-title">
        This dashboard displays shop-related sales data, including shop city distribution, top-performing shops,
        city-wise shop counts and sales, as well as queries about specific shop sales and profits.
      </p>
    </div>

    <!-- Content section -->
    <div class="content-section">
      <!-- Filter section -->
      <div class="filter-section">
        <!-- Main filter: date, city and sales -->
        <el-form :inline="true" :model="mainFilterForm" class="main-filter">
          <el-form-item>
            <el-date-picker
              v-model="mainFilterForm.dateRange"
              type="daterange"
              range-separator="to"
              start-placeholder="Start Date"
              end-placeholder="End Date"
              value-format="YYYY-MM-DD"
              style="width: 260px" />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="mainFilterForm.city"
              placeholder="Select City"
              clearable
              style="width: 200px">
              <el-option
                v-for="item in cities"
                :key="item"
                :label="item"
                :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="mainFilterForm.operator"
              placeholder="Sales Compare"
              clearable
              style="width: 150px">
              <el-option label="=" value="=" />
              <el-option label="<" value="<" />
              <el-option label="<=" value="<=" />
              <el-option label=">" value=">" />
              <el-option label=">=" value=">=" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="mainFilterForm.operator">
            <el-input
              v-model="mainFilterForm.amount"
              placeholder="Enter Amount"
              style="width: 150px" />
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button type="primary" @click="handleMainFilter">
                <el-icon>
                  <Search />
                </el-icon>
                Filter
              </el-button>
              <el-button @click="resetMainFilter">
                <el-icon>
                  <Refresh />
                </el-icon>
                Reset
              </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>

      <!-- Main content area -->
      <el-row :gutter="20">
        <!-- Left ranking chart -->
        <el-col :span="8">
          <el-card class="chart-card" shadow="hover">
            <div class="chart-title">Top 15 Shops by Sales and Profit</div>
            <ECharts :options="rankingChartOptions" height="860px" />
          </el-card>
        </el-col>

        <!-- Right content -->
        <el-col :span="16">
          <!-- Right upper section -->
          <div class="right-upper">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-card class="chart-card" shadow="hover">
                  <div class="chart-title">
                    Shop City Distribution
                    <el-icon
                      class="chart-type-switch"
                      @click="togglePieChartType"
                      :title="getNextPieTypeTitle(currentPieChartType)">
                      <component :is="getPieChartTypeIcon(currentPieChartType)" />
                    </el-icon>
                  </div>
                  <ECharts :options="getCityDistributionChartOptions(currentPieChartType)" height="300px" />
                </el-card>
              </el-col>
              <el-col :span="16">
                <el-card class="chart-card" shadow="hover">
                  <div class="chart-title">City Sales Data</div>
                  <ECharts :options="citySalesOptions" height="300px" />
                </el-card>
              </el-col>
            </el-row>
          </div>

          <!-- Right lower section -->
          <div class="right-lower">
            <!-- Shop filter: shop and product category -->
            <el-form :inline="true" :model="shopFilterForm" class="shop-filter">
              <el-form-item>
                <el-select
                  v-model="shopFilterForm.shopId"
                  placeholder="Select Shop"
                  clearable
                  style="width: 200px">
                  <el-option
                    v-for="item in shops"
                    :key="item"
                    :label="`Shop ${item}`"
                    :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select
                  v-model="shopFilterForm.category"
                  placeholder="Product Category"
                  clearable
                  style="width: 200px">
                  <el-option
                    v-for="item in categories"
                    :key="item"
                    :label="item"
                    :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-button type="primary" @click="handleShopFilter">
                    <el-icon>
                      <Search />
                    </el-icon>
                    Filter
                  </el-button>
                  <el-button @click="resetShopFilter">
                    <el-icon>
                      <Refresh />
                    </el-icon>
                    Reset
                  </el-button>
                </el-button-group>
              </el-form-item>
            </el-form>
            <!-- KPI cards and trend chart -->
            <el-row :gutter="20">
              <el-col :span="10">
                <div class="kpi-wrapper">
                  <div class="kpi-section">
                    <div v-for="(kpi, index) in kpiData" :key="index">
                      <el-card class="kpi-card" shadow="hover">
                        <div class="kpi-title">{{ kpi.title }}</div>
                        <div class="kpi-value">{{ kpi.value }}</div>
                        <div class="kpi-trends">
                          <div class="trend-item">
                            <div class="trend-label">Week-over-Week</div>
                            <div :class="['trend-value', kpi.weekOnWeek > 0 ? 'up' : 'down']">
                              <el-icon>
                                <CaretTop v-if="kpi.weekOnWeek > 0" />
                                <CaretBottom v-else />
                              </el-icon>
                              {{ Math.abs(kpi.weekOnWeek).toFixed(2) }}%
                            </div>
                          </div>
                          <div class="trend-item">
                            <div class="trend-label">Day-over-Day</div>
                            <div :class="['trend-value', kpi.dayOnDay > 0 ? 'up' : 'down']">
                              <el-icon>
                                <CaretTop v-if="kpi.dayOnDay > 0" />
                                <CaretBottom v-else />
                              </el-icon>
                              {{ Math.abs(kpi.dayOnDay).toFixed(2) }}%
                            </div>
                          </div>
                        </div>
                      </el-card>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :span="14">
                <el-card class="chart-card" shadow="hover">
                  <div class="chart-title">
                    Shop Sales and Profit Trend
                    <el-icon
                      class="chart-type-switch"
                      @click="toggleChartType(1)"
                      :title="getNextChartTypeTitle(currentChartType[1])">
                      <component :is="getChartTypeIcon(currentChartType[1])" />
                    </el-icon>
                  </div>
                  <ECharts :options="getSalesTrendChartOptions(currentChartType[1])" height="350px" />
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { CaretTop, CaretBottom, Search, Refresh, TrendCharts, DataLine, Histogram } from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts.vue'
import { getFilterOptions, getShopAnalysis } from '@/api/analysis'
import { ElMessage } from 'element-plus'

// 主筛选表单数据（日期、城市和销售额）
const mainFilterForm = reactive({
  dateRange: [],
  city: '',
  operator: '',
  amount: ''
})

// 商店筛选表单数据（商店和产品类别）
const shopFilterForm = reactive({
  shopId: '',
  category: ''
})

// 选项数据
const categories = ref([])
const cities = ref([])
const shops = ref([])

// 图表数据
const chartData = ref({
  kpiData: {
    totalSales: 0,
    salesWeekOnWeek: 0,
    salesDayOnDay: 0,
    totalVolume: 0,
    volumeWeekOnWeek: 0,
    volumeDayOnDay: 0
  },
  rankingData: {
    shops: [],
    sales: [],
    profits: []
  },
  cityData: {
    distribution: [],
    sales: {
      cities: [],
      sales: [],
      volumes: []
    }
  },
  shopTrend: {
    months: [],
    sales: [],
    profits: []
  }
})

// 饼图类型状态
const currentPieChartType = ref('pie')

// 图表类型状态
const chartTypes = ['bar', 'line', 'area']
const currentChartType = ref(['bar', 'bar']) // 每个图表的初始类型

// 获取下一个饼图类型的提示文字
const getNextPieTypeTitle = (currentType) => {
  switch (currentType) {
    case 'pie': return '切换为环形图'
    case 'ring': return '切换为漏斗图'
    case 'funnel': return '切换为饼图'
    default: return '切换图表类型'
  }
}

// 获取当前饼图类型的图标
const getPieChartTypeIcon = (type) => {
  switch (type) {
    case 'pie': return TrendCharts
    case 'ring': return DataLine
    case 'funnel': return Histogram
    default: return TrendCharts
  }
}

// 切换饼图类型
const togglePieChartType = () => {
  currentPieChartType.value = currentPieChartType.value === 'pie' ? 'ring' : currentPieChartType.value === 'ring' ? 'funnel' : 'pie'
}

// 获取下一个图表类型的提示文字
const getNextChartTypeTitle = (currentType) => {
  switch (currentType) {
    case 'line': return '切换为面积图'
    case 'area': return '切换为柱状图'
    case 'bar': return '切换为折线图'
    default: return '切换图表类型'
  }
}

// 获取当前图表类型的图标
const getChartTypeIcon = (type) => {
  switch (type) {
    case 'bar':
      return TrendCharts
    case 'line':
      return DataLine
    case 'area':
      return Histogram
    default:
      return TrendCharts
  }
}

// 切换图表类型
const toggleChartType = (index) => {
  const currentIndex = chartTypes.indexOf(currentChartType.value[index])
  const nextIndex = (currentIndex + 1) % chartTypes.length
  currentChartType.value[index] = chartTypes[nextIndex]
}
// 获取城市分布图表选项
const getCityDistributionChartOptions = (type) => {
  let options = {}
  options = {
    tooltip: {
      trigger: 'item',
      show: type === 'funnel' ? false : true,
    },
    series: [{
      type: type === 'ring' ? 'pie' : type,
      radius: type === 'ring' ? ['30%', '50%'] : '50%',
      data: chartData.value.cityData.distribution,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        show: type === 'funnel' ? false : true,
        formatter: '{b}: {d}%'
      }
    }]
  }
  return options
}

// 获取销售趋势图表选项
const getSalesTrendChartOptions = (type) => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['Sales', 'Profit']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.shopTrend.months
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: value => `$${formatKNumber(value)}`
      }
    },
    series: [
      {
        name: 'Sales',
        type: type === 'area' ? 'line' : type,
        data: chartData.value.shopTrend.sales,
        areaStyle: type === 'area' ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(64, 158, 255, 0.6)'
            }, {
              offset: 1,
              color: 'rgba(64, 158, 255, 0)'
            }]
          }
        } : null
      },
      {
        name: 'Profit',
        type: type === 'area' ? 'line' : type,
        data: chartData.value.shopTrend.profits,
        areaStyle: type === 'area' ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(103, 194, 58, 0.6)'
            }, {
              offset: 1,
              color: 'rgba(103, 194, 58, 0)'
            }]
          }
        } : null
      }
    ]
  }
}

// 获取筛选选项数据
const loadFilterOptions = async () => {
  try {
    const options = await getFilterOptions()
    categories.value = options.categories
    cities.value = options.cities
    shops.value = options.shops
  } catch (error) {
    ElMessage.error('Failed to load filter options, please refresh the page')
  }
}

// 获取排名和城市数据
const fetchRankAndCityData = async () => {
  try {
    const params = {
      startDate: mainFilterForm.dateRange[0] || null,
      endDate: mainFilterForm.dateRange[1] || null,
      city: mainFilterForm.city,
      operator: mainFilterForm.operator,
      amount: mainFilterForm.amount
    }

    const data = await getShopAnalysis(params)
    if (data) {
      // 倒序显示排名数据
      chartData.value.rankingData = {
        shops: data.rankingData?.shops?.reverse() || [],
        sales: data.rankingData?.sales?.reverse() || [],
        profits: data.rankingData?.profits?.reverse() || []
      }
      chartData.value.cityData = data.cityData || {
        distribution: [],
        sales: {
          cities: [],
          sales: [],
          volumes: []
        }
      }
    }
  } catch (error) {
    ElMessage.error('Failed to fetch ranking and city data, please try again')
  }
}

// 获取商店KPI和趋势数据
const fetchShopData = async () => {
  try {
    // 验证是否选择了商店或产品类别
    if (!shopFilterForm.shopId && !shopFilterForm.category) {
      ElMessage.warning('Please select at least one shop or product category')
      return
    }

    const params = {
      startDate: mainFilterForm.dateRange[0] || null,
      endDate: mainFilterForm.dateRange[1] || null,
      shopId: shopFilterForm.shopId,
      category: shopFilterForm.category
    }

    const data = await getShopAnalysis(params)
    if (data) {
      // 只更新KPI和趋势数据
      chartData.value.kpiData = data.kpiData || {
        totalSales: 0,
        salesWeekOnWeek: 0,
        salesDayOnDay: 0,
        totalVolume: 0,
        volumeWeekOnWeek: 0,
        volumeDayOnDay: 0
      }
      chartData.value.shopTrend = data.shopTrend || {
        months: [],
        sales: [],
        profits: []
      }
    }
  } catch (error) {
    ElMessage.error('Failed to fetch shop data, please try again')
  }
}

// 处理主要筛选（日期、城市和销售额）
const handleMainFilter = async () => {
  // 验证销售额筛选条件
  if (mainFilterForm.operator && !mainFilterForm.amount) {
    ElMessage.warning('Please enter the sales amount')
    return
  }

  // 验证是否有任何筛选条件
  if (!mainFilterForm.dateRange?.length && !mainFilterForm.city && !mainFilterForm.operator) {
    ElMessage.warning('Please select at least one filter condition')
    return
  }

  await fetchRankAndCityData()
}

// 处理商店筛选（商店和产品类别）
const handleShopFilter = async () => {
  await fetchShopData()
}

// 重置主要筛选
const resetMainFilter = () => {
  mainFilterForm.dateRange = []
  mainFilterForm.city = ''
  mainFilterForm.operator = ''
  mainFilterForm.amount = ''
  fetchRankAndCityData()
}

// 重置商店筛选
const resetShopFilter = () => {
  shopFilterForm.shopId = ''
  shopFilterForm.category = ''
  // 清空KPI和趋势数据
  chartData.value.kpiData = {
    totalSales: 0,
    salesWeekOnWeek: 0,
    salesDayOnDay: 0,
    totalVolume: 0,
    volumeWeekOnWeek: 0,
    volumeDayOnDay: 0
  }
  chartData.value.shopTrend = {
    months: [],
    sales: [],
    profits: []
  }
}

// KPI数据
const kpiData = computed(() => [
  {
    title: 'Total Sales',
    value: formatCurrency(chartData.value.kpiData.totalSales),
    weekOnWeek: chartData.value.kpiData.salesWeekOnWeek,
    dayOnDay: chartData.value.kpiData.salesDayOnDay
  },
  {
    title: 'Total Sales Volume',
    value: formatNumber(chartData.value.kpiData.totalVolume),
    weekOnWeek: chartData.value.kpiData.volumeWeekOnWeek,
    dayOnDay: chartData.value.kpiData.volumeDayOnDay
  }
])

// 排名图表配置
const rankingChartOptions = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: params => {
      return params.map(param => {
        const value = param.seriesName === 'Sales' ?
          `$${formatNumber(param.value)}` :
          formatNumber(param.value)
        return `${param.name}<br/>${param.seriesName}: ${value}`
      }).join('<br/>')
    }
  },
  legend: {
    data: ['Sales', 'Profit']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    axisLabel: {
      formatter: value => `${formatKNumber(value)}`
    }
  },
  yAxis: {
    type: 'category',
    data: chartData.value.rankingData.shops
  },
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: chartData.value.rankingData.sales,
      label: {
        show: false
      }
    },
    {
      name: 'Profit',
      type: 'bar',
      data: chartData.value.rankingData.profits,
      label: {
        show: false
      }
    }
  ]
}))

// 城市分布图表配置
const cityDistributionOptions = computed(() => ({
  tooltip: {
    trigger: 'item',
    formatter: params => {
      return `${params.name}<br/>count: ${formatNumber(params.value)}<br/>percent: ${params.percent}%`
    }
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: chartData.value.cityData.distribution,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      label: {
        formatter: '{b}: {d}%'
      }
    }
  ]
}))

// 城市销售数据图表配置
const citySalesOptions = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    },
    formatter: params => {
      return params.map(param => {
        const value = param.seriesName === 'Sales' ?
          `$${formatNumber(param.value)}` :
          `${formatNumber(param.value)}`
        return `${param.name}<br/>${param.seriesName}: ${value}`
      }).join('<br/>')
    }
  },
  legend: {
    data: ['Sales', 'Sales Volume']
  },
  grid: {
    left: '3%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartData.value.cityData.sales.cities
  },
  yAxis: [
    {
      type: 'value',
      name: 'Sales',
      position: 'left',
      axisLabel: {
        formatter: value => `$${formatKNumber(value)}`
      }
    },
    {
      type: 'value',
      name: 'Sales Volume',
      position: 'right',
      axisLabel: {
        formatter: value => `${formatKNumber(value)}`
      }
    }
  ],
  series: [
    {
      name: 'Sales',
      type: 'bar',
      data: chartData.value.cityData.sales.sales,
      label: {
        show: false
      }
    },
    {
      name: 'Sales Volume',
      type: 'line',
      yAxisIndex: 1,
      data: chartData.value.cityData.sales.volumes,
      label: {
        show: false
      }
    }
  ]
}))

// 商店趋势图表配置
const shopTrendOptions = computed(() => ({
  tooltip: {
    trigger: 'axis',
    formatter: params => {
      return params.map(param => {
        return `${param.name}<br/>${param.seriesName}: $${formatNumber(param.value)}`
      }).join('<br/>')
    }
  },
  legend: {
    data: ['Sales', 'Profit']
  },
  xAxis: {
    type: 'category',
    data: chartData.value.shopTrend.months,
    axisLabel: {
      formatter: value => value.toLowerCase()
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: value => `${formatKNumber(value)}`
    }
  },
  series: [
    {
      name: 'Sales',
      type: 'line',
      data: chartData.value.shopTrend.sales,
      smooth: true,
      label: {
        show: false
      }
    },
    {
      name: 'Profit',
      type: 'line',
      data: chartData.value.shopTrend.profits,
      smooth: true,
      label: {
        show: false
      }
    }
  ]
}))

// 格式化数字（完整显示）
const formatNumber = (value) => {
  if (!value) return '0'
  return new Intl.NumberFormat('zh-CN').format(value)
}

// 格式化货币
const formatCurrency = (value) => {
  if (!value) return '0'
  return formatNumber(value)
}

// 格式化数字（K/M/B）
const formatKNumber = (value) => {
  if (!value) return '0'
  if (value >= 1000000000) {
    return (value / 1000000000).toFixed(1) + 'B'
  }
  if (value >= 1000000) {
    return (value / 1000000).toFixed(1) + 'M'
  }
  if (value >= 1000) {
    return (value / 1000).toFixed(1) + ''
  }
  return value.toString()
}

onMounted(() => {
  loadFilterOptions()
  fetchRankAndCityData()  // 初始只加载排名和城市数据
})
</script>

<style scoped>
.shop-analysis {
  width: calc(100vw - 400px);
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.header-section {
  padding: 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
}

.sub-title {
  font-size: 14px;
  color: #5e6d82;
  margin: 0;
}

.content-section {
  padding: 24px;
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.main-filter,
.shop-filter {
  padding: 15px;
  background-color: #f8f9fb;
  border-radius: 4px;
  margin-bottom: 15px;
}

.shop-filter {
  border-top: 1px solid #e4e7ed;
}

.filter-section :deep(.el-form--inline) {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-section :deep(.el-form-item) {
  margin-right: -6px;
  margin-bottom: 0;
}

.filter-section :deep(.el-button-group) {
  display: flex;
  gap: 8px;
}

.filter-section :deep(.el-button) {
  display: flex;
  align-items: center;
  gap: 4px;
}

.right-upper {
  margin-bottom: 20px;
}

.kpi-wrapper {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
}

.kpi-section {
  margin-bottom: 0;
}

.kpi-section>div:not(:last-child) {
  margin-bottom: 16px;
}

.kpi-card {
  padding: 0 16px;
  background-color: #F8FAFC;
  border: 1px solid #E4E7ED;
  height: 160px;
}

.kpi-card:hover {
  background-color: #F2F6FC;
  border-color: #DCDFE6;
}

.kpi-title {
  color: #409EFF;
  font-size: 14px;
  padding-top: 16px;
  margin-bottom: 8px;
}

.kpi-value {
  font-size: 24px;
  margin-bottom: 16px;
}

.kpi-trends {
  padding-bottom: 8px;
  gap: 8px;
}

.trend-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.trend-label {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
  color: #909399;
}

.trend-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.trend-value.up {
  color: #f56c6c;
}

.trend-value.down {
  color: #67c23a;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  color: #303133;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__body) {
  padding: 0;
}

.chart-type-switch {
  cursor: pointer;
  color: #909399;
  font-size: 18px;
}

.chart-type-switch:hover {
  color: #409EFF;
  background-color: #ecf5ff;
}
</style>